package com.samp.tools.lire;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import net.semanticmetadata.lire.builders.DocumentBuilder;
import net.semanticmetadata.lire.imageanalysis.features.global.CEDD;
import net.semanticmetadata.lire.searchers.GenericFastImageSearcher;
import net.semanticmetadata.lire.searchers.ImageSearchHits;
import net.semanticmetadata.lire.searchers.ImageSearcher;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SearchImage {
	
	private static final Logger logger = LoggerFactory.getLogger(SearchImage.class);
	
	private static final float MAX_DIFF = 40.0f;
	
	private  List<ImageSearchResultDTO> searchImageBySeriesIdAndStream(String seriesIndexPath, String fileTempPath,String cImageId ) throws IOException{
		BufferedImage img =null;
		File file = new File(fileTempPath);
		img = ImageIO.read(file);
		IndexReader ir = DirectoryReader.open(FSDirectory.open(Paths.get(seriesIndexPath)));
		ImageSearcher searcher = new GenericFastImageSearcher(30, CEDD.class);
		ImageSearchHits hits = searcher.search(img, ir);
		logger.debug("hits.length()="+hits.length());
		//int count = hits.length() >= 50 ? 50 : hits.length();
		int count = hits.length();
		ArrayList<ImageSearchResultDTO> resultList = new ArrayList<ImageSearchResultDTO>();
		for (int i = 0; i < count; i++) {
			if( hits.score(i) > MAX_DIFF ){
				continue;
			}
			String imageId = ir.document(hits.documentID(i)).getValues(DocumentBuilder.FIELD_NAME_IDENTIFIER)[0];
			if( imageId.equals(cImageId) ){
				logger.info("oooooooooooooooooooooooooookkkk!");
			}
			logger.debug("return imageid=: "+imageId+",score="+ hits.score(i));
			resultList.add(new ImageSearchResultDTO(imageId, hits.score(i)));
		}
		logger.debug("resultList.size()="+resultList.size());
		return resultList;
	}
	
	public void searchByImageId(String seriesIndexPath, String imageId) throws Exception{
		FSDirectory directory = FSDirectory.open(Paths.get(seriesIndexPath));
		DirectoryReader reader = DirectoryReader.open(directory);
		IndexSearcher searcher = new IndexSearcher(reader);
		TopDocs result = searcher.search(new TermQuery(new Term(DocumentBuilder.FIELD_NAME_IDENTIFIER,imageId)), 10);
		if( result != null && result.scoreDocs.length > 0 ){
			logger.debug("has indexed,scoreDocs.length"+result.scoreDocs.length );
			ScoreDoc[] hits = result.scoreDocs;
			for(int i = 0 ; i < hits.length ; i++ ){
				logger.debug("docNum="+hits[i].doc+",docScore="+hits[i].score);
				Document doc = searcher.doc(hits[i].doc);
				logger.debug(doc.get(DocumentBuilder.FIELD_NAME_IDENTIFIER));
				//这两上为null，应该是只索引了，没有存储。
				logger.debug(doc.get(DocumentBuilder.FIELD_NAME_CEDD));
				logger.debug(doc.get(DocumentBuilder.FIELD_NAME_FCTH));
			}
		}else{
			logger.debug("has not indexed");
		}
		reader.close();
		directory.close();
	}
	
	public static void main(String[] args) {
		SearchImage si = new SearchImage();
		String seriesIndexPath = "D:\\nas\\paus\\ci\\paus\\201806251106044201";
		String fileTempPath = "D:\\nas\\paus\\images\\1531981608392.jpg";
		String imageId = "711CDEE14BC72435E055000100D202EF";
		try {
			//si.searchImageBySeriesIdAndStream(seriesIndexPath,fileTempPath,imageId);
			si.searchByImageId(seriesIndexPath, imageId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("done!");
	}

	class ImageSearchResultDTO {
	    private double difference;
	    private String imageId;

	    public ImageSearchResultDTO() {
	       super();
	    }
	    
		public ImageSearchResultDTO(String imageId, double difference) {
	        this.imageId = imageId;
	        this.difference = difference;
	    }

		public String getImageId() {
			return imageId;
		}

		public void setImageId(String imageId) {
			this.imageId = imageId;
		}

		public double getDifference() {
			return difference;
		}

		public void setDifference(double difference) {
			this.difference = difference;
		}
		
	}
}
